const User = require('../models/User');
const jwt = require('jsonwebtoken');
const express = require('express');
const router = express.Router();
const authenticate = require('../middlewares/auth');
const bcrypt = require('bcryptjs');

// 注册接口
router.post('/register', async (req, res) => {
  try {
    // 添加字段空值校验
    if (!req.body.account) {
      return res.status(400).json({ message: '账户不能为空' });
    }

    const existingUser = await User.findOne({ account: req.body.account });
    if (existingUser) {
      return res.status(400).json({ message: '账户已存在' });
    }

    // 创建新用户
    const newUser = new User({
      username: req.body.username,
      account: req.body.account,
      password: req.body.password,
      personality: req.body.personality
    });

    await newUser.save();
    res.status(201).json({
      message: '注册成功',
    });
  } catch (error) {
    // 捕获 MongoDB 唯一性错误
    if (error.code === 11000) {
      return res.status(400).json({
        message: '账户已存在',
        field: error.keyValue.account ? 'account' : 'unknown'
      });
    }
    res.status(500).json({ message: '注册失败', error: error.message });
  }
});

// 登录接口
router.post('/login', async (req, res) => {
  try {

    if (!req.body.account || !req.body.password) {
      return res.status(400).json({
        code: 400,
        message: '账户和密码不能为空'
      });
    }

    const user = await User.findOne({ account: req.body.account })
      .select('+password')
      .lean();

    if (!user) return res.status(401).json({ 
      code: 401,
      message: '账户不存在' 
    });

    const isMatch = await bcrypt.compare(req.body.password, user.password);
    if (!isMatch) return res.status(401).json({ 
      code: 401,
      message: '密码错误' 
    });

    const token = jwt.sign(
      { userId: user._id },
      process.env.JWT_SECRET,
      { expiresIn: '8h' }
    );

    res.json({
      code: 200,
      data: {
        token,
        user: {
          id: user._id,
          username: user.username,
          avatar: user.avatar,
          personality: user.personality
        }
      },
      message: '登录成功'
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '系统异常',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
});

// 获取用户信息（需要JWT认证）
router.get('/profile', authenticate, async (req, res) => {
  try {
    // 排除avatar字段
    const user = await User.findById(req.userId)
      .select('-password -__v -updatedAt -avatar')
      .lean();

    if (!user) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      });
    }

    res.json({
      code: 200,
      data: {
        ...user,
        id: user._id.toString(),
        createdAt: user.createdAt.toISOString()
      },
      message: '获取成功'
    });
  } catch (error) {
    console.error('用户信息获取失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
});

// 更新用户信息路由
router.patch('/profile', authenticate, async (req, res) => {
  try {
    // 允许更新的字段白名单
    const allowedUpdates = ['username', 'avatar', 'personality'];
    const updates = Object.keys(req.body)
      .filter(key => allowedUpdates.includes(key))
      .reduce((obj, key) => {
        obj[key] = req.body[key];
        return obj;
      }, {});

    if (Object.keys(updates).length === 0) {
      return res.status(400).json({
        code: 400,
        message: '没有提供有效更新字段'
      });
    }

    // 执行更新并返回新数据
    const user = await User.findByIdAndUpdate(
      req.userId,
      updates,
      { new: true, runValidators: true }
    ).select('-password -__v');

    res.json({
      code: 200,
      data: user,
      message: '资料更新成功'
    });

  } catch (error) {
    console.error('用户信息更新失败:', error);
    const statusCode = error.name === 'ValidationError' ? 400 : 500;
    res.status(statusCode).json({
      code: statusCode,
      message: error.message || '更新失败'
    });
  }
});

// 在路由中添加测试接口
router.get('/verify-secret', (req, res) => {
  try {
    jwt.sign({}, process.env.JWT_SECRET);
    res.send('密钥配置正确');
  } catch (e) {
    res.status(500).send('密钥配置错误');
  }
});

module.exports = router;